package com.link.base.base.product.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.link.base.base.common.dao.mybatis.mapper.AttachmentMapper;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.product.dao.mybatis.mapper.PartsCostTempMapper;
import com.link.base.base.product.model.PartsCostTemp;
import com.link.base.base.product.model.PartsCostTempData;
import com.link.base.core.basic.util.YmlConstants;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.CallParam;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 成本信息汇总临时对象
 *
 * @date 2023-08-15 09:04:14
 */
@Service
public class PartsCostTempServiceImpl extends BasicServiceImpl<PartsCostTemp> implements PartsCostTempService {

    @Resource
    private PartsCostTempMapper    partsCostTempMapper;

    @Resource
    private AttachmentMapper attachmentMapper;

    @Override
    public BasicMapper<PartsCostTemp> getBasicMapper() {
        return partsCostTempMapper;
    }

    private static final String pattern = "^[1-9]\\d*|0$";


    @Override
    public void insertExcelData(Long attachmentId) throws Exception {
        Attachment param = new Attachment();
        param.setId(attachmentId);
        Attachment attachment = attachmentMapper.queryById(param);
        if (null == attachment.getHeadId()) {
            throw new RuntimeException("数据导入异常：项目Id丢失!");
        }
        String excelPath = YmlConstants.getPortalShareFileDir() + attachment.getAttachmentFilePath();
        ExcelReaderBuilder excelReaderBuilder =
                EasyExcel.read(excelPath,
                        PartsCostTempData.class,
                        new PartsCostTempListener(partsCostTempMapper, UserUtil.getUser(), attachment.getHeadId()));
        //获取一个工作表
        ExcelReaderSheetBuilder sheet = excelReaderBuilder.sheet();
        //读取工作表内容:sheet方法参数：工作表的顺序号（从0开始）或者工作表的名字，不传默认为0
        sheet.doRead();
    }

    @Override
    public String runDataCheck(PartsCostTemp record) throws Exception {
        if (null == record.getProjectId()) {
            throw new RuntimeException("项目Id丢失，请联系管理员!");
        }
        List<PartsCostTemp> list =  partsCostTempMapper.queryAll(record);
        List<PartsCostTemp> checkFailList = new ArrayList<>();
        List<PartsCostTemp> checkSuccessList = new ArrayList<>();
        for (PartsCostTemp partsCostTemp : list) {
            boolean isValidateFlag = true;
            // 物料层级
            String wlmc = partsCostTemp.getWlmc();
            String wlmcHead = partsCostTemp.getWlmcHead();
            String wlmcTail = partsCostTemp.getWlmcTail();
            if (StringUtils.isNull(wlmc) || StringUtils.isNull(wlmcHead)) {
                checkFailList.add(partsCostTemp);
                isValidateFlag = false;
            } else {
                if (!wlmcHead.matches(pattern)) {
                    checkFailList.add(partsCostTemp);
                    isValidateFlag = false;
                } else {
                    if (!StringUtils.isNull(wlmcTail) && !wlmcTail.matches(pattern)) {
                        checkFailList.add(partsCostTemp);
                        isValidateFlag = false;
                    }
                }
            }
            // 校验通过，则添加到校验成功队列里面
            if (isValidateFlag) {
                checkSuccessList.add(partsCostTemp);
            }
        }
        // 校验失败处理
        if (!CollectionUtils.isEmpty(checkFailList)) {
            partsCostTempMapper.updateCheckFail(checkFailList);
        }
        // 校验成功处理
        if (!CollectionUtils.isEmpty(checkSuccessList)) {
            partsCostTempMapper.updateCheckSuccess(checkSuccessList);
        }
        return "本次校验成功：" + checkSuccessList.size() + "条，校验失败：" + checkFailList.size() + "条!";
    }

    @Override
    public CallParam runDataImport(PartsCostTemp record) throws Exception {
        if (null == record.getProjectId()) {
            throw new RuntimeException("项目Id丢失，请联系管理员!");
        }
        CallParam callParam = new CallParam();
        callParam.setParam1(record.getCreatedBy());
        callParam.setParam2(String.valueOf(record.getProjectId()));
        partsCostTempMapper.runDataImport(callParam);
        return callParam;
    }

    @Override
    public void deleteAll(PartsCostTemp partsCostTemp) throws Exception {
        partsCostTempMapper.deleteAll(partsCostTemp);
    }
}
